package com.wwt.server.config.security;

import com.wwt.server.pojo.Admin;
import com.wwt.server.service.IAdminService;
import com.wwt.server.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * Spring Security配置类
 */
@Configuration
@EnableWebSecurity
public class MySecurityConfig extends WebSecurityConfigurerAdapter implements WebMvcConfigurer {

    @Autowired
    //@Lazy
    private IAdminService adminService;
    @Autowired
    private MyAuthenticationEntryPoint authenticationEntryPoint;
    @Autowired
    private MyAccessDenyHandler accessDenyHandler;
    //@Autowired
    //private JWTAuthenticationTokenFilter  jwtAuthenticationTokenFilter;
    @Autowired
    private CustomFilter customFilter;
    @Autowired
    private CustomUrlDecisionManager customUrlDecisionManager;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService()).passwordEncoder(passwordEncoder());
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.
                authorizeRequests().
                //antMatchers("/login").permitAll().
                anyRequest().authenticated().
                //动态权限管理
                withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
                    @Override
                    public <O extends FilterSecurityInterceptor> O postProcess(O o) {
                        o.setAccessDecisionManager(customUrlDecisionManager);
                        o.setSecurityMetadataSource(customFilter);
                        return o;
                    }
                }).
                and().
                csrf().disable().  //jwt不用考虑跨站请求伪造
                headers().cacheControl();  //禁用缓存
        http.sessionManagement().sessionCreationPolicy((SessionCreationPolicy.STATELESS));
        //在后者过滤器之前添加自定义的过滤器
        http.addFilterBefore(jwtAuthenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class);
        //添加自定义未授权和未登录结果返回
        http.exceptionHandling().
                accessDeniedHandler(accessDenyHandler).
                authenticationEntryPoint(authenticationEntryPoint);
    }
    //基于全局安全配置

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers(
                "/login/**",
                "/logout",
                "/doc.html",
                "/jss/**",
                "/css/**",
                "/index.html",
                "/favicon.ico",
                //"/doc.html",
                "/webjars/**",   //jar包形式的静态资源
                "/swagger-resources/**",
                "/v2/api-docs/**",
                "/kaptcha/**",
                "/img/**"
                );
    }

    @Autowired
    private IRoleService roleService;
    //重写UserDetailsService 即重写LoadByUsername的逻辑
    @Override
    @Bean
    public UserDetailsService userDetailsService() {
        return username -> {
            Admin admin = adminService.getAdminInfo(username);
            if (admin != null){
                admin.setRoles(roleService.getRolesByAdminId(admin.getId()));
                return admin;
            }
            throw new UsernameNotFoundException("用户名或密码错误");
        };
    }

    //解决静态资源无法访问问题
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/img/**")
                .addResourceLocations("classpath:/img/");
    }

    @Bean(value = "passwordEncoder")
    public BCryptPasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
    @Bean
    public JWTAuthenticationTokenFilter jwtAuthenticationTokenFilter(){
        return new JWTAuthenticationTokenFilter();
    }

}
